// toast - 展示处理中
export function toastLoading(title,duration) {
    uni.showLoading({
    	title:isBlank(title)?`处理中...`:title,
		mask:true,
		duration:isBlank(duration)?1500:duration
    })
}

// toast - 隐藏
export function toastHide() {
    uni.hideLoading()
}

// toast - 展示成功
export function toastSuccess(text,event) {
    uni.showToast({
		mask:true,
    	title:(isBlank(text)?"成功":text)
    })
	setTimeout(()=>{
		if(isNotNull(event)){
			event()
		}
	},1500)
}

// toast - 错误
export function toastError(text,event) {
    uni.showToast({
		image:"/static/wxicon/error.png",
		mask:true,
    	title:(isBlank(text)?"错误":text)
    })
	setTimeout(()=>{
		if(isNotNull(event)){
			event()
		}
	},1500)
}

// toast - 展示成功后返回
function toastSuccessBack(text,params) {
    uni.showToast({
		mask:true,
    	title:(isBlank(text)?"成功":text),
		success: () => {
			if(params){
				//如果是事件，则出发
				if(params instanceof Function){
					setTimeout(()=>{
						params()
					},1500)
				}else if(params instanceof Object){
					//如果是对象，则返回
					uni.$emit("update",params)
				}
			}else{
				uni.$emit("update",true)
			}
		}
    })
}

// 展示模态 - 温馨提示
export function modalInfo(content,confirmEvent,cancelEvent) {
	uni.showModal({
		title:"温馨提示",
		content:content,
		confirmText:"确认",
		showCancel:isNotNull(cancelEvent),
		cancelText:isNotNull(cancelEvent)?"取消":"",
		success: (res) => {
			if(res.confirm){
				if(isNotNull(confirmEvent)){
					confirmEvent()
				}
			}else{
				if(isNotNull(cancelEvent)){
					cancelEvent()
				}
			}
		}
	})
}

// 展示模态 - 警告提示
export function modalWarin(content) {
	uni.showModal({
		title:"警告",
		content:content,
		confirmText:"确认",
		showCancel:false
	})
}

// 展示模态 - 系统提示
export function modalError(content) {
	uni.showModal({
		title:"系统提示",
		content:content,
		confirmText:"确认",
		showCancel:false
	})
}

/**
 * 返回首页
 * @param {Object} page
 */
export function fanhuiShouye(){
	uni.reLaunch({
		url:"/pages/index/index"
	})
}

/**
 * 将一个对象的属性添加到另一个对象
 * @param {Object} option
 */
export function obj2obj(originObj,targetObj,isToNull) {
    for (let key in originObj) {
		if(isNull(isToNull) || isToNull){
			targetObj[key] = originObj[key]
		}else{
			if(originObj.hasOwnProperty(key) && isNotNull(originObj[key])){
				targetObj[key] = originObj[key]
			}
		}
    }
}

/**
 * 移除空值
 * @param {Object} option
 */
export function removeNull(option) {
    if (!option) {
        return;
    }
    for (var attr in option) {
        if (option[attr] === null) {
            delete option[attr];
            continue;
        }
        if (typeof (option[attr]) == "object") {
            removeNull(option[attr]);
        }
    }
}

/**
 * 是否不为空
 * @param {Object} params
 */
function isNull(str){
      if (typeof(str) === 'undefined'){
		  return true
	  }else if(str == null){
		  return true
	  }
	  return false
}

/**
 * 是否不为空
 * @param {Object} params
 */
function isNotNull(params){
      if (typeof(params) === 'undefined'){
		  return false
	  }else if(params == null){
		  return false
	  }
	  
	  return true
}

/**
 * 字符串是否为空
 * @param {Object} params
 */
function isBlank(str){
	console.info("isBlank",str)
      if (typeof(str) === 'undefined'){
		  return true
	  }else if(str == null){
		  return true
	  }else if((typeof str === "string") && str.trim() == ''){
		  return true
	  }
	  return false
}

/**
 * 字符串是否为空
 * @param {Object} params
 */
function isNotBlank(str){
	  return !isBlank(str)
}

/**
 * 表单校验是否为空
 * @param {Object} params
 */
function formIsBlank(str){
	let result = false
      if (
      typeof(str) === 'undefined' || 
      str == null ||
      (typeof(str) === 'string' && str === '') ||
      typeof(str) === 'number' && str <= 0){
      		  result = true
      }
	  
	  return result
}

/**
 * 表单校验是否不为空
 * @param {Object} params
 */
function formIsNotBlank(str){
	let result = true
	
      if (
	  typeof(str) === 'undefined' || 
	  str == null ||
	  (typeof(str) === 'string' && str === '') ||
	  typeof(str) === 'number' && str <= 0){
		  result = false
	  }
	  
	  return result
}

/**
 * 获取字符串中某个字符数量
 * @param {Object} scrstr
 * @param {Object} armstr
 */
function getCharCountFromStr(scrstr,armstr) {
    var count=0;
    while(scrstr.indexOf(armstr) != -1 ) {
       scrstr = scrstr.replace(armstr,"")
       count++;    
    }
    return count;
}


/**
 * 字符串中是否包含某个字符
 * @param {Object} v
 */
function isHaveCharFromStr(str,char){
	let count = getCharCountFromStr(str,char)
	if(count <= 0){
		return false
	}else{
		return true
	}
}

/**
 * 输入分数返回值
 * @param {Object} jine
 */
function getFenshuWidthFiexd(fenshu,fiexd){
	console.info("getFenshuWidthFiexd:参数",fenshu,fiexd)
	if(isBlank(fenshu)){
		return ''
	}
	let result = fenshu
	
	let fArray = fenshu.split(".")
	console.info("getFenshuWidthFiexd:分组",fArray)
	if(fArray.length == 1){
	}else if(fArray.length == 2){
		let f2 = fArray[1]
		let lCha = f2.length - fiexd
		if(lCha > 0){
			result = fenshu.substr(0,fenshu.length - lCha)
		}
	}else{
		result = fArray[0] + '.' + fArray[1]
	}
	
	console.info("getFenshuWidthFiexd:结果",result)
	return result
}

/**
 * 跳转
 * @param {Object} url
 * @param {Object} params
 */
function navigateTo (url,params){
	let zUrl = url
	if(isNull(params)){
		params = {}
	}
	console.info(params)
	let paramsUrl = ""
	for (let paramKey in params) {
		paramsUrl += paramKey + "=" + params[paramKey] + "&"
	}
	if(paramsUrl.endsWith("&")){
		paramsUrl = paramsUrl.substr(0,paramsUrl.length -1)
	}
	
	if(paramsUrl != ""){
		if(isHaveCharFromStr(zUrl,"?")){
			zUrl += "&" + paramsUrl
		}else{
			zUrl += "?" + paramsUrl
		}
	}
	console.info(zUrl)
	uni.navigateTo({
		url:zUrl,
		success: (res) => {
			console.info("跳转成功",res,url,params)
		},
		fail: (res) => {
			console.info("跳转失败",res,url,params)
		}
	})
}

/**
 * 获取系统设备id
 */
function getSysDeviceId(type){
	let sysInfo = uni.getSystemInfoSync()
	return sysInfo.deviceId
}

/**
 * 展示客服
 */
function showKefu(){
	uni.showModal({
		title:"客服中心",
		content:"加微信：17329275632",
		confirmText:"复制号码",
		success: (res) => {
			if(res.confirm){
				uni.setClipboardData({
				    data: '17329275632',
				    success:()=> {
						showToastSuccess("已复制")
				    }
				});
			}
		}
	})
}

/**
 * 文件分享
 * @param {Object} url
 * @param {Object} fileName
 */
function fileShare(url,fileName){
	// let url = "https://www.yanwei.xin:8501/jzjz/export/6cdc0ec3025a44f8abc7de4fa79015d3/(闫伟)闫伟工地资料.xls"
	let fileFullPath =  wx.env.USER_DATA_PATH + "/" + getUUID(true) + "." + url.split(".")[url.split(".").length-1]
	console.info("fileFullPath",fileFullPath)
	wx.downloadFile({
	  url: url, // 下载url
	  filePath: fileFullPath,
	  success (res) {
		  console.info("下载文档参数",res)
	    // 下载完成后转发
	    wx.shareFileMessage({
			filePath: fileFullPath,
			fileName: fileName,
			success() {},
			fail:(err)=>{
				console.info("分享文档失败",err)
				showModalError("分享文档失败,请联系客服。",JSON.stringify(err))
		  }
	    })
	  },
	  fail:(err)=>{
		console.info("下载文件失败",err)
	  	showModalError("下载文件失败,请联系客服。",JSON.stringify(err))				  
	  }
	})
}

/**
 * 预览图片
 * @param {Object} url
 */
function filePreview(url) {
	// this.$common.filePreview("https://www.yanwei.xin:8501/jzjz/export/6cdc0ec3025a44f8abc7de4fa79015d3/(闫伟)闫伟工地资料.xls")
	// let fileDir = wx.env.USER_DATA_PATH + "/" + getUUID(true)
	let fileDir = wx.env.USER_DATA_PATH + "/" + url.split("/")[url.split("/").length-2]
	let fileFullPath =  fileDir + "/" + url.split("/")[url.split("/").length-1]
	console.info("文件全路径",fileFullPath)
	const fs = wx.getFileSystemManager()
	uni.downloadFile({
		url:url,      //文件链接
		success:(resDownload)=>{
			console.info("下载成功",resDownload)
			//statusCode状态为200表示请求成功，tempFIlePath临时路径
			if(resDownload.statusCode==200){
				//保存到本地
				uni.saveFile({
					tempFilePath:resDownload.tempFilePath,
					success:(res)=>{
						fs.mkdirSync(fileDir, true)
						fs.copyFile({
						  srcPath: res.savedFilePath,
						  destPath: fileFullPath,
						  success:(res)=> {
						    console.log("复制成功",res)
							//res.savedFilePath文件的保存路径
							 //保存成功并打开文件
							 uni.openDocument({
								showMenu:true,
								filePath:fileFullPath,
								success:(res)=>console.log('成功打开文档'),
								fail: (err) => {
									console.info("打开文档失败",err)
									showModalError("打开文档失败,请联系客服。",JSON.stringify(err))
								}
							})
						  },
						  fail(err) {
						    console.error("复制文档失败",err)
							showModalError("保存文档失败,请联系客服。",JSON.stringify(err))
						  }
						})
					},
					fail: (err) => {
						console.info("保存失败",err)
						showModalError("保存文档失败,请联系客服。",JSON.stringify(err))
					}
				})
			}
		},
		fail: (err) => {
			console.info("下载失败",err)
			showModalError("下载文档失败,请联系客服。",JSON.stringify(err))
		}
	})
}

/**
 * 校验字符串格式
 * @param {Object} type phone
 * @param {Object} str
 */
function checkStr(type,str){
	//参考文章https://www.jb51.net/article/238570.htm
	let phone = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
	let email = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/

	switch(type){
		case "phone":
			return phone.test(str)
		break
		case "email":
			return email.test(str)
		break
	}
	
	return null;
}

/**
 * 获取uuid
 * @param {Object} isNoHenggang
 */
function getUUID (isNoHenggang) {
  var s = [];
  var hexDigits = "0123456789abcdef";
  for (var i = 0; i < 36; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
  }
  s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
  s[8] = s[13] = s[18] = s[23] = "-";
 
  var uuid = s.join("");
  if(isNoHenggang){
	  uuid = uuid.replace(/-/g,'')
  }
  return uuid
}

export const common = {
	toastLoading:toastLoading,
	toastHide:toastHide,
	toastSuccess:toastSuccess,
	toastError:toastError,
	toastSuccessBack:toastSuccessBack,
	
	modalInfo:modalInfo,
	modalWarin:modalWarin,
	modalError:modalError,
	
	fanhuiShouye:fanhuiShouye,
	obj2obj:obj2obj,
	removeNull:removeNull,
	
	isNull:isNull,
	isNotNull:isNotNull,
	isBlank:isBlank,
	isNotBlank:isNotBlank,
	formIsBlank:formIsBlank,
	formIsNotBlank:formIsNotBlank,
	
	getCharCountFromStr:getCharCountFromStr,
	isHaveCharFromStr:isHaveCharFromStr,
	getFenshuWidthFiexd:getFenshuWidthFiexd,
	
	getSysDeviceId:getSysDeviceId,
	
	showKefu:showKefu,
	
	navigateTo:navigateTo,
	fileShare:fileShare,
	filePreview:filePreview,
	
	checkStr:checkStr,
	getUUID:getUUID,
}

export default common 